<?php
class CommonAction extends Action {
	function _initialize() {
		//编码统一设置 成 UTF8格式 
		header("Content-Type:text/html;Charset=utf-8");
		// 用户权限检查

	
	}
	
	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
		return;
	}
	/**
     +----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模块的默认操作
	 * 可以在action控制器中重载
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	function getReturnUrl() {
		return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
		$name=$this->getActionName();
		$model = D ( $name );
		$map = array ();
		foreach ( $model->getDbFields () as $key => $val ) {
			if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
				$map [$val] = $_REQUEST [$val];
			}
		}
		return $map;

	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _list($model, $map, $sortBy = '', $asc = false) {
		//排序字段 默认为主键名
		if (isset ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		$orderby = $order.' '.$sort;
		if($order !==$model->getPk()) $orderby .= ', '.$model->getPk().' desc';
		//取得满足条件的记录数
		$count = $model->where ( $map )->count ( '"'.$model->getPk() .'"');
		if ($count > 0) {
			import ( "@.ORG.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['listRows'] )) {
				$listRows = $_REQUEST ['listRows'];
			} else {
				$listRows = '';
			}
			$p = new Page ( $count, $listRows );
			//分页查询数据

			//$voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
			$voList = $model->where($map)->order( $orderby )->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//dump($voList);
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		Cookie::set ( '_currentUrl_', __SELF__ );
		return;
	}

	function insert() {
		//B('FilterString');
		//处理表单其他内容
		$name=$this->getActionName();
		
		
		
		/*需要先插入user表中一个新的用户
			
			$model_array = array('Building','Agent','Corporation','Park');
			if (in_array($name, $model_array)) {
    			
    			$user= new UserModel();
				$time = time();
			
				$userfield['password']='670b14728ad9902aecba32e22fa4f6bd';
				$userfield['name']='000000';
				$userfield['email']='000000';
				$userfield['status']= 0;		 
				$userfield['created']=$time;
				$userfield['updated']= $time;				
				$userfield['account']= $name.'_'.md5(uniqid(microtime(),true)).mt_rand();
				$user_id = $user->data($userfield)->add();
				if( false === $user_id){
					$this->error('用户ID未成功获取');
				}
			}			
		
		*/
		
		$model = D ($name);
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		if($_POST["created"]){$model->created	=  strtotime($_POST["created"]);}
		//处理略缩图，此处应该可以读取config文件，本机不能读，请具体更改
		//如果设置了图片，则处理上传，其他不具普适情况者，重写insert()
		if ($_FILES['picture']['name'])
		{ 
		
			import("ORG.Net.UploadFile");
			$upload = new UploadFile(); // 实例化上传类
			$upload->maxSize  = '3145728'; // 设置附件上传大小
			$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
			$upload->savePath =  $_SERVER['DOCUMENT_ROOT'].'/Public/Uploads/Images/'; // 设置附件上传目录
			$upload->saveRule = 'time';//文件命名规则
			$upload->subType = 'hash';
			$upload->hashLevel = 3;
			$upload->autoSub = true;//子目录存放
			if(!$upload->upload()) { // 上传错误提示错误信息
				$this->error($upload->getErrorMsg());
			}else{ // 上传成功获取上传文件信息
				$file_info =  $upload->getUploadFileInfo();
			}
			//保存图片内容
			$model->picture = __PUBLIC__.'/Uploads/Images/'.$file_info[0]["savename"];
		}
		
		//保存当前数据对象		
		
		//$model->user_id=$user_id;

		$list=$model->add ();
		
		/*
		 * 处理关键词
		 */
		if ($list!==false) { //保存成功
			//处理关键词
			$keyword = M('Keyword');
			$articlekey = M('Keyworddata');
			$module = M('Module');
			
			$data['data_id'] = $list;
			
			$title = empty($_POST['title'])?$_POST['name']:$_POST['title'];
	
			$data['title'] = $title;
			$data['created'] = time();
			$data['status'] = 1;
			
			$data['table_id'] = $module->where('module="'.$name.'"')->getField('id');
			

			$keys = explode(' ',trim($_POST['keyword']));
			foreach($keys as $key){
				$key = trim($key);				
				$keyid = $keyword->where('keyword="'.$key.'"')->getField('id');
				if(empty($keyid)){
					$keydata['keyword'] = $key;					
					$keyid = $keyword->data($keydata)->add();
					$data['key_id'] = $keyid;					
				}else{
					$data['key_id'] = $keyid;
				}
				$articlekey->data($data)->add();				
			}
			
			
			//处理自定义字段
			if(is_array($_POST['addonfield']))
			{
				$fielddata = A('Fielddata');
				$fielddata->savefielddata($_POST['addonfield'],$list); 
			}
			
			//$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
            $this->assign ( 'jumpUrl', $this->getReturnUrl() );
			$this->success ('新增成功!');

		} else {
			//失败提示
			$this->error ('新增失败!');
		}
	}
	
	public function add() {
		$this->display ();
	}
	
	function read() {
		$this->edit ();
	}

	function edit() {
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );
		$this->assign ( 'vo', $vo );
		$this->display ();
	}

	function update() {
		//B('FilterString');

		$name=$this->getActionName();
		$model = D ( $name );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		if($_POST["created"]){
			$model->created	=  strtotime($_POST["created"]);		
		}

		//处理略缩图，此处应该可以读取config文件，本机不能读，请具体更改
		//如果设置了图片，则处理上传，其他不具普适情况者，重写update()

		if ($_FILES['picture']['name'])
		{
			import("ORG.Net.UploadFile");
			$upload = new UploadFile(); // 实例化上传类
			$upload->maxSize  = '3145728'; // 设置附件上传大小
			$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
			$upload->savePath =  $_SERVER['DOCUMENT_ROOT'].'/Public/Uploads/Images/'; // 设置附件上传目录
			$upload->saveRule = 'time';//文件命名规则
			$upload->subType = 'hash';
			$upload->hashLevel = 3;
			$upload->autoSub = true;//子目录存放
			if(!$upload->upload()) { // 上传错误提示错误信息
				$this->error($upload->getErrorMsg());
			}else{ // 上传成功获取上传文件信息
				$file_info =  $upload->getUploadFileInfo();
			}
			//保存图片内容
			$model->picture = __PUBLIC__.'/Uploads/Images/'.$file_info[0]["savename"];
		}
		
		// 更新数据
		$list=$model->save ();
		//echo $model->getlastsql();

		/*
		 * 处理关键词
		 */
		if (false !== $list) {
			
			$keyword = M('Keyword');
			$Keydata = M('Keyworddata');
			$module = M('Module');
			
			$data['data_id'] = $_POST['id'];
	
			$title = empty($_POST['title'])?$_POST['name']:$_POST['title'];
			
			$data['title'] = $title;
			$data['status'] = 1;
			
			$data['table_id'] = $module->where('module="'.$name.'"')->getField('id');
			
			$Keydata->where('data_id='.$_POST['id'].' and table_id='.$data['table_id'])->delete();
				
			$keys = explode(' ',trim($_POST['keyword']));
			foreach($keys as $key){
				$key = trim($key);				
				$keyid = $keyword->where('keyword="'.$key.'"')->getField('id');
				if(empty($keyid)){
					$keydata['keyword'] = $key;					
					$keyid = $keyword->data($keydata)->add();
					$data['key_id'] = $keyid;					
				}else{
					$data['key_id'] = $keyid;
				}
				$Keydata->data($data)->add();				
			}
			
			//处理自定义字段
			if(is_array($_POST['addonfield']))
			{
				$fielddata = A('Fielddata');
				$fielddata->savefielddata($_POST['addonfield'],$_POST['id']); 
			}
		
			//成功提示
			//$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
            $this->assign ( 'jumpUrl', $this->getReturnUrl() );
			$this->success ('编辑成功!');
		} else {
			//错误提示
			$this->error ('编辑失败!');
		}
	}
	/**
     +----------------------------------------------------------
	 * 默认删除操作
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	public function delete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = M ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				$list=$model->where ( $condition )->setField ( 'status', - 1 );
				if ($list!==false) {
					$this->success ('删除成功！' );
				} else {
					$this->error ('删除失败！');
				}
			} else {
				$this->error ( '非法操作' );
			}
		}
	}
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					//echo $model->getlastsql();
					$this->success ('删除成功！');
				} else {
					$this->error ('删除失败！');
				}
			} else {
				$this->error ( '非法操作' );
			}
		}
		$this->forward ();
	}

	public function clear() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			if (false !== $model->where ( 'status=1' )->delete ()) {
				$this->assign ( "jumpUrl", $this->getReturnUrl () );
				$this->success ( L ( '_DELETE_SUCCESS_' ) );
			} else {
				$this->error ( L ( '_DELETE_FAIL_' ) );
			}
		}
		$this->forward ();
	}
	/**
     +----------------------------------------------------------
	 * 默认禁用操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	public function forbid() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$field = $_REQUEST['field'] ? $_REQUEST['field'] : 'status';
		$condition = array ($pk => array ('in', $id ) );
		$list=$model->forbid ( $condition, $field);

		if ($list!==false) {
		
			$Keydata = M('Keydata');
			$module = M('Module');

			$tableid = $module->where('module="'.$name.'"')->getField('id');
			
			$Keydata->where('data_id='.$_GET['id'].' and table_id='.$tableid)->setField('status','0');
			//$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
            $this->assign ( 'jumpUrl', $this->getReturnUrl() );
			$this->success ( '状态禁用成功' );
		} else {
			$this->error  (  '状态禁用失败！' );
		}
	}
	public function checkPass() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->checkPass( $condition )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态批准成功！' );
		} else {
			$this->error  (  '状态批准失败！' );
		}
	}

	public function recycle() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->recycle ( $condition )) {

			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态还原成功！' );

		} else {
			$this->error   (  '状态还原失败！' );
		}
		
	}

	public function recycleBin() {
		$map = $this->_search ();
		$map ['status'] = - 1;
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
	}

	/**
     +----------------------------------------------------------
	 * 默认恢复操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	function resume($field='status') {
		//恢复指定记录
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$field = $_REQUEST['field'] ? $_REQUEST['field'] : 'status';
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->resume ( $condition, $field )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态恢复成功！' );
		} else {
			$this->error ( '状态恢复失败！' );
		}
	}

	/*
	 * 排序函数
	 * 表单提交
	 * 必须有sort字段
	 * 接收来自$_POST['sort'],获取排序数组
	 */
	public function sort()
    {
    	$name = $this->getActionName();
		$sort = $_POST['sort'];
		$model = M($name);
		$id = $model->getPk();
		if(is_array($sort))
		{
			foreach ($sort as $key => $value )
			{
				$data[$id] = $key;
				$data['sort'] = $value;
				$model->save($data);
			}
		}
		$this->success('排序成功');
    }

	function saveSort() {
		$seqNoList = $_POST ['seqNoList'];
		if (! empty ( $seqNoList )) {
			//更新数据对象
			$name=$this->getActionName();
			$model = D ($name);
			$col = explode ( ',', $seqNoList );
			//启动事务
			$model->startTrans ();
			foreach ( $col as $val ) {
				$val = explode ( ':', $val );
				$model->id = $val [0];
				$model->sort = $val [1];
				$result = $model->save ();
				if (! $result) {
					break;
				}
			}
			//提交事务
			$model->commit ();
			if ($result!==false) {
				//采用普通方式跳转刷新页面
				$this->success ( '更新成功' );
			} else {
				$this->error ( $model->getError () );
			}
		}
	}
	
	//获得某一分类的所有子分类，并用“,”连接成字符串
	function getAllChild($id){
		$childs = $this -> getChild($id);
		if (is_array($childs)) {
			foreach($childs as $key=>$a){
					$this->ret .= ','.$a['id'];
				$this->getAllChild($a['id']);
			}
		}
		return $this->ret;
	}
	
	//获得某一分类的下一级子分类，协助与方法getChild()，递归调用
	function getChild($pid){
		$a = $newarr = array();
		if(is_array($this->inList))
		{
			foreach($this->inList as $id => $a)
			{
				if($a['pid'] == $pid) $newarr[$id] = $a;
			}
		}
		return $newarr ? $newarr : false;
	}
	function stachange(){
		$name=$this->getActionName();
		$model = D ($name);
		$ids = $_POST['id'];
		foreach($ids as $id){
			$data['id'] = $id;
			$data['status'] = 0;
			$model->save($data);
		}
		$this->success('删除成功');
	}
	function del(){
		$name=$this->getActionName();
		$model = D ($name);
		$ids = $_POST['id'];
		foreach($ids as $id){
			$model->where('id='.$id)->delete(); 
		}
		$this->success('删除成功');
	}
	function stachangetrue(){
		$name=$this->getActionName();
		$model = D ($name);
		$ids = $_POST['id'];
		foreach($ids as $id){
			$data['id'] = $id;
			$data['status'] = 1;
			$model->save($data);
		}
		$this->success('恢复成功');
	}


}
?>
